class HistoryKeyword {
    static MAX_ITEM_COUNT = 20;
    static KEY = "keywords";

    keywords = [];

    constructor() {
        if (typeof HistoryKeyword.instance === 'object') {
            return HistoryKeyword.instance;
        }
        HistoryKeyword.instance = this;
        this.keywords = this._getLocalKeywords();
        return this;
    }

    save(keyword) {
        //判断keyword是否在keywords数组中重复，如果重复，直接返回
        const items = this.keywords.filter(k => k === keyword);
        if (items.length !== 0) {
            return;
        }
        //判断当前keywords数组中是否超出最大存储量，如果超出，就把先进来的元素删除
        if (this.keywords.length > HistoryKeyword.MAX_ITEM_COUNT) {
            this.keywords.pop();
        }
        //把keyword加到数组前面，push（）是加到数组后面。
        this.keywords.unshift(keyword);
        //刷新缓存
        this._refreshLocal();
    }

    get() {
        return this.keywords;
    }

    /**
     * 清除数据
     */
    clear() {
        this.keywords = [];
        //刷新缓存
        this._refreshLocal();
    }

    /**
     * 保存数据到缓存中
     * @private
     */
    _refreshLocal() {
        wx.setStorageSync(HistoryKeyword.KEY, this.keywords);
    }

    /**
     * 从缓存中取出数据
     * @returns {*[]}
     * @private
     */
    _getLocalKeywords() {
        const keywords = wx.getStorageSync(HistoryKeyword.KEY);
        if (!keywords) {
            wx.setStorageSync(HistoryKeyword.KEY, []);
            return [];
        }
        return keywords;
    }

}

export {
    HistoryKeyword
}